package com.scorekeeper.objects;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcel;

import com.scorekeeper.utils.DBProvider;

public final class Games 
	extends DBProvider 
	implements DBObject  
{
	public int _id;
	public Date gameDate;
	public int homeTeamId;
	public int awayTeamId;
	public int homeScore;
	public int awayScore;
	public int seasonId;
	
	public Games(Context context) {
		super(context);
		this._id = -1;
		this.homeTeamId = 0;
		this.awayTeamId = 0;
		this.seasonId = 0;
	}
	
	@Override
	public int describeContents() { return hashCode(); }
	
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeLong(this._id);
		dest.writeValue(this.gameDate);
		dest.writeInt(this.homeTeamId);
		dest.writeInt(this.awayTeamId);
	}
	
	@Override
	public void loadFromParcel(Parcel loadFrom) {
		this._id = loadFrom.readInt();
		this.gameDate = (Date) loadFrom.readValue(Date.class.getClassLoader());
		this.homeTeamId = loadFrom.readInt();
		this.awayTeamId = loadFrom.readInt();
		this.homeScore = loadFrom.readInt();
		this.awayScore = loadFrom.readInt();
	}
	
	@Override
	public ContentValues loadContentValues() {
		ContentValues cv = new ContentValues();
		
		cv.put("GameDate", this.gameDate.getTime());
		cv.put("HomeTeamId", this.homeTeamId);
		cv.put("AwayTeamId", this.awayTeamId);
		cv.put("HomeScore", this.homeScore);
		cv.put("AwayScore", this.awayScore);
		cv.put("SeasonId", this.seasonId);
		
		return cv;
	}
	
	@Override
	public void save() {
		this.open();
		
		if (this._id != -1) {
			//update
			this.update(Table.GAME.Name(), loadContentValues(), "Id=?", new String[] { Integer.toString(this._id) } );
		} else {
			//insert
			this._id = (int) this.insert(Table.GAME.Name(), loadContentValues());
		}
		
		this.close();
	}

	@Override
	public void delete() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean load(int id) {
		this._id = id;
		return load();
	}

	@Override
	public boolean load() {
		boolean rv = false;
		
		this.open();
		
		//ensure a valid id
		if (this._id != -1) {
			Cursor cur = this.select("SELECT * FROM GAME WHERE Id = ?", new String[] { Integer.toString(this._id) });
			if (this.isValidCursor(cur)) {
				this._id = cur.getInt(0);
				this.gameDate = new Date(cur.getLong(1));
				this.homeTeamId = cur.getInt(2);
				this.awayTeamId = cur.getInt(3);
				this.homeScore = cur.getInt(4);
				this.awayScore = cur.getInt(5);
				rv = true;
			}
		}
		
		this.close();
		return rv;
	}
}
